package ci.web.codec;

import io.netty.handler.codec.http.FullHttpRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 对HTTP_POST直接按照JSON格式进行解码
 * @author zhh
 */
public class JsonPostDecoder extends FormPostDecoder {

	public JsonPostDecoder(FullHttpRequest request) throws Exception {
		super(request);
	}

	@Override
	protected void decode() throws Exception {
		this.files = EMPTY_FILES;
		this.bodyDatas = EMPTY_BODYDATAS;
		
		byte[] jsonBytes = new byte[request.content().readableBytes()];
		request.content().getBytes(request.content().readerIndex(), jsonBytes);
		
		Object data = JSON.parse(jsonBytes);
		if(data instanceof JSONObject){
		    this.paramters = (JSONObject) data;
		}else{
		    this.paramters = new JSONObject();
		    if(data instanceof JSONArray){
	            JSONArray arr = (JSONArray)data;
	            for(int i=0;i<arr.size();i++){
	                paramters.put(i+"", arr.get(i));
	            }
		    }
		}
	}
	
	/**
	 * don't need clean
	 */
    public void clean() {

    }

}
